package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2020/5/6.
 */
@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;
    @RequestMapping("/login")
    @ResponseBody
    //HttpSession session抽取工具类可不要这个参数了
    public JsonResult login(String username, String password){
        try {
/*            Employee employee = employeeService.login(username, password);
            //把员工存到session中
//            session.setAttribute("EMPLOYEE_IN_SESSION",employee);
            UserContext.setCurrentUser(employee);
            //如果不是管理员才需要查询权限
            if(!employee.isAdmin()){
                //把员工的权限表达式集合存到session中
                //获取当前用户已经拥有的权限表达式集合
                List<String> permissonExpressions = permissionService.selectByEmpId(employee.getId());
//                session.setAttribute("PERMISSON_IN_SESSION",permissonExpressions);
            UserContext.setPermissionExpression(permissonExpressions);
            }*/
            //封装令牌
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);
            //利用shiro进行登录
            SecurityUtils.getSubject().login(token);
            return new JsonResult();
        } catch (UnknownAccountException e){
            return new JsonResult(false,"账号不存在");
        }
         catch (IncorrectCredentialsException e){
            return new JsonResult(false,"密码错误");
        }
         catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"登录异常,请联系管理员");
        }
    }
//    @RequestMapping("/logout")
//    public String logout(HttpSession session){
//        //销毁会话
//        session.invalidate();
//        return "redirect:/login.html";
//    }
}
